package com.lb.uts.web;

import com.lb.uts.constants.UTSConstants;
import com.lb.uts.exception.UTSException;
import com.lb.uts.service.IActiveSchedulingService;
import com.lb.uts.entity.ActiveScheduling;
import com.lb.uts.service.policy.ISchedulingPolicy;
import com.lb.uts.util.IdUtils;
import com.lb.uts.util.PolicyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

/**
 * 描述：实现{@link ApplicationRunner}完成初始数据的加载
 * 用于执行策略的缓存。
 * 作者：liangb
 * 日期：2018/10/15
 * 时间：16:45
 */
@Component
public class UtsApplicationRunner implements ApplicationRunner {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private IActiveSchedulingService activeSchedulingService;

    private final String FILE_NAME = "/META-INF/scheduling_policy.internal/com.tritonsfs.cac.uts.service.policy.ISchedulingPolicy";

    @Value("${server.port}")
    private String port;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //保存调度器信息
        //本地ip
        String exeIp = InetAddress.getLocalHost().getHostAddress();
        ActiveScheduling activeScheduling = new ActiveScheduling();
        exeIp = exeIp + ":" + port;
        activeScheduling.setIp(exeIp);
        List<ActiveScheduling> activeSchedulings = activeSchedulingService.queryByEntity(activeScheduling);
        if (activeSchedulings.isEmpty()) {
            activeScheduling.setId(IdUtils.nextUUID());
            activeScheduling.setCreateTime(LocalDateTime.now());
            int num = activeSchedulingService.insert(activeScheduling);
            if (num == 0) {
                throw new UTSException("9999", "调度器注册失败");
            }
        }
        UTSConstants.LOCAL_IP_PORT = exeIp;
        //读取策略处理的service
        //读取poweretc.internal下的文件
        Properties props = new Properties();
        InputStream fileInputStream = this.getClass().getResourceAsStream(FILE_NAME);
        props.load(fileInputStream);
        //进行缓存
        Enumeration<?> enu = props.propertyNames();
        while (enu.hasMoreElements()) {
            Object key = enu.nextElement();
            Object value = props.get(key);
            PolicyUtil.schedulingPolicyMap.put(key.toString(), (ISchedulingPolicy) (applicationContext.getBean(Class.forName(value.toString()))));
        }
    }
}
